#!/bin/bash

if GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null); then
    TOP_DIR="$GIT_ROOT"
else
    SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
    TOP_DIR="$SCRIPT_DIR"
fi

export ZSH="$TOP_DIR"
WORK_DIR="${ZSH}/scripts"

cmd_start() {
  # 确保工作目录存在（避免后续操作报错）
  mkdir -p "${WORK_DIR}" 2>/dev/null
  echo "工作目录: $WORK_DIR"

  echo "1. 更新代码"
  cd "$ZSH" && git pull --rebase

  echo "2. 更新配置文件"
  cp -r "$ZSH"/configs/.vimrc "$HOME"/.vimrc
  cp -r "$ZSH"/configs/.zshrc "$HOME"/.zshrc
  if [ -d "/work" ]; then
    sudo mkdir /work
    sudo chmod 777 /work
  fi
  if [ -d "/work/bin" ]; then
    mkdir -p /work/bin
  fi
  if [[ -z $OS_TYPE ]];then
    cp -r "$ZSH/configs/$OS_TYPE/.bashconfig" /work/bin/.bashconfig
    cp -r "$ZSH/configs/$OS_TYPE/.bashconfig" "$HOME"/.bashconfig
  fi
}

cmd_complete() {
  zsh
  return 0
}

# 系统专属操作函数（直接接收并使用传递的参数）
cmd_ubuntu() {
  echo "更新 ubuntu 环境变量"
}

cmd_centos() {
  echo "更新 centos 环境变量"
}

cmd_macos() {
#  echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
#  echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
#  echo 'eval "$(pyenv init -)"' >> ~/.zshrc
#
#  # 使配置生效
#  source ~/.zshrc
  echo "更新 macos 环境变量"
}

cmd_windows() {
  echo "更新 windows 环境变量"
}

cmd_wsl() {
  echo "更新 wsl 环境变量"
}

cmd_unknown() {
  echo "未知系统，暂不更新环境变量"
}

# shellcheck disable=SC3046
. "$WORK_DIR"/common_os.sh || source "$WORK_DIR"/common_os.sh

# 启动主程序并传递所有参数
main "$@"
